package com.demo.config.datasource.annotation;


import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author wangfengchen
 */
@Aspect
@Component
@Order(Ordered.HIGHEST_PRECEDENCE) // 确保在事务切面之前执行
public class DataSourceAspect {

  @Pointcut("@annotation(com.demo.config.datasource.annotation.DS)")
  public void dsPointCut() {
  }

  @Around("dsPointCut()")
  public Object around(ProceedingJoinPoint point) throws Throwable {
    // 根据方法名自动选择数据源（如 get/select开头的方法走从库）
//    String methodName = point.getSignature().getName();
//    if (methodName.startsWith("get") || methodName.startsWith("select")) {
//      DataSourceContextHolder.setDataSourceKey("slave");
//    } else {
//      DataSourceContextHolder.setDataSourceKey("master");
//    }

    MethodSignature signature = (MethodSignature) point.getSignature();
    Method method = signature.getMethod();
    DS dsAnnotation = method.getAnnotation(DS.class);

    if (dsAnnotation != null) {
      String dsKey = dsAnnotation.value().getDesc();
      DynamicDataSourceContextHolder.setDataSourceKey(dsKey); // 设置数据源
    }

    try {
      return point.proceed(); // 执行方法
    } finally {
      DynamicDataSourceContextHolder.clearDataSourceKey(); // 清除数据源
    }
  }
}